<template>
	<div style="position: relative;">
		<el-card shadow="hover">
			<GoBack @back="goBack" />
			<div class="pa40">
				<el-form ref="form" :model="formData.data" :rules="formData.rules" label-width="110px">
					<el-form-item ref="face" label="员工头像" prop="face"><UploadImage :fileUrl="formData.data.face" @input="getPicUrl('face', $event)" /></el-form-item>
					<el-form-item ref="userName" label="姓名" prop="userName">
						<el-input :disabled="routeInfo.type === 'edit'" v-model.trim="formData.data.userName" maxlength="10" show-word-limit placeholder="请输入姓名" />
					</el-form-item>
					<el-form-item ref="realName" label="昵称" prop="realName">
						<el-input v-model.trim="formData.data.realName" maxlength="10" show-word-limit placeholder="请输入昵称" />
					</el-form-item>
					<el-form-item ref="phone" label="手机号" prop="phone">
						<el-input v-model.trim="formData.data.phone" placeholder="请输入手机号" maxlength="11" @input="filterNum" />
					</el-form-item>
					<el-form-item ref="sex" label="性别" prop="sex">
						<el-radio-group v-model="formData.data.sex">
							<el-radio :label="1">男</el-radio>
							<el-radio :label="2">女</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item ref="isManagement" label="是否管理员" prop="isManagement">
						<el-radio-group v-model="formData.data.isManagement">
							<el-radio :label="1">是</el-radio>
							<el-radio :label="2">否</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item ref="roles" label="系统角色" prop="roles">
						<el-select v-model="formData.data.roles" multiple placeholder="请选择系统角色" class="w100">
							<el-option v-for="item in roleList" :key="item.id" :label="item.rName" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item ref="state" label="是否在职" prop="state">
						<el-radio-group v-model="formData.data.state">
							<el-radio :label="1">是</el-radio>
							<el-radio :label="2">否</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item ref="account" label="登录账号" prop="account">
						<el-input v-model.trim="formData.data.account" maxlength="20" show-word-limit placeholder="请输入登录账号" />
					</el-form-item>
					<el-form-item ref="pwd" label="登录密码" prop="pwd">
						<el-input v-model.trim="formData.data.pwd" maxlength="20" show-word-limit placeholder="请输入登录密码" />
					</el-form-item>
					<el-form-item v-if="routeInfo.type === 'add' || routeInfo.type === 'edit'">
						<el-button :loading="formData.loading" type="primary" @click="onSubmit">完成</el-button>
					</el-form-item>
				</el-form>
			</div>
		</el-card>
	</div>
</template>

<script lang="ts">
import { defineComponent, toRefs, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from '/@/store/index.ts'
import GoBack from '/@/components/GoBack/index.vue'
import UploadImage from '/@/components/UploadImage/index.vue'
import { ElMessage, ElNotification } from 'element-plus'
import { defaultAddUserData, getSysUserByUserId, addSysUser, updateSysUser } from '/@/api/staff'
import { getRoleList } from '/@/api/role'
import scrollForm from '/@/utils/scrollForm'
import Base64 from '/@/utils/base64'
import { setSession } from '/@/utils/storage.ts'
import { verifiyNumberInteger } from '/@/utils/toolsValidate'
import { clearSession } from '/@/utils/storage.ts'
import { resetRoute } from '/@/router/index.ts'

export default defineComponent({
	name: 'operationStaff',
	components: { GoBack, UploadImage },
	setup() {
		const store = useStore()
		const router = useRouter()
		const route = useRoute()

		const refs = reactive({
			form: null,
			face: null,
			userName: null,
			realName: null,
			phone: null,
			sex: null,
			isManagement: null,
			roles: null,
			state: null
		})

		const state = reactive({
			routeInfo: {},
			roleList: [],
			formData: {
				data: JSON.parse(JSON.stringify(defaultAddUserData)),
				loading: false,
				rules: {
					face: [{ required: true, message: '请上传员工头像', trigger: 'blur' }],
					userName: [{ required: true, message: '1-10个字，支持中英文、数字', trigger: 'blur' }],
					realName: [{ required: true, message: '1-10个字，支持中英文、数字', trigger: 'blur' }],
					phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
					sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
					isManagement: [{ required: true, message: '请选择是否管理员', trigger: 'blur' }],
					roles: [{ required: true, message: '请选择系统权限', trigger: ['blur', 'change'] }],
					state: [{ required: true, message: '请选择性别', trigger: 'blur' }]
				}
			}
		})

		const goBack = () => {
			router.push({
				path: '/system/staff',
				query: {}
			})
		}

		// 正整数
		const filterNum = (val: string) => {
			state.formData.data.order = verifiyNumberInteger(val)
		}

		// 获得图片路径
		const getPicUrl = (field, val) => {
			if (typeof val === 'string') state.formData.data[field] = val
		}

		const onSubmit = () => {
			refs.form.validate(async (valid: boolean, object: object) => {
				if (valid) {
					state.formData.loading = true

					if (state.routeInfo.type === 'add') {
						await addSysUser(state.formData.data).finally(() => {
							state.formData.loading = false
						})
						ElMessage.success('新增成功！')
					} else {
						await updateSysUser(state.formData.data).finally(() => {
							state.formData.loading = false
						})

						//如果改的是当前用户，则需要重新登录
						if (store.state.userInfos.userInfos.userId === state.formData.data.id) {
							clearSession() // 清除浏览器全部临时缓存
							resetRoute() // 删除/重置路由

							ElNotification.success('编辑成功！当前登录信息已失效，请重新登录！')
						} else {
							ElMessage.success('编辑成功！')
						}
					}

					router.push({
						path: '/system/staff',
						query: {
							refresh: true
						}
					})
				} else {
					scrollForm(refs, object)
				}
			})
		}

		const getRoleListApi = () => {
			getRoleList({}).then(res => {
				const { datas = [] } = res

				state.roleList = datas
			})
		}

		// 页面加载时
		onMounted(() => {
			state.routeInfo = JSON.parse(Base64(route.query.info, 2))
			getRoleListApi()

			//给pid赋值
			state.formData.data.pid = state.routeInfo.pid

			if (state.routeInfo.type === 'edit' || state.routeInfo.type === 'show') {
				getSysUserByUserId({ userId: state.routeInfo.id }).then(res => {
					const { datas } = res
					state.formData.data = datas
					state.formData.data.roles = state.formData.data.roleList ? state.formData.data.roleList.map(x => x.id) : []
				})
			}
		})
		return {
			goBack,
			filterNum,
			getPicUrl,
			onSubmit,
			...toRefs(refs),
			...toRefs(state)
		}
	}
})
</script>

<style></style>
